using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MyPhotoIndex.VersionCheck;
using MyPhotoIndex.Settings;
using System.Diagnostics;
using MyPhotoIndex.UpdateCheckServiceProxy;
using System.Net;
using System.IO;
using MyPhotoIndex.Utilities;
using System.Reflection;
using System.Threading;
using System.Runtime.InteropServices;
using System.Globalization;
using MyPhotoIndex.Controls;

namespace MyPhotoIndex.VersionCheck
{
    public partial class VersionCheckForm : FormTemplate
    {
        private bool m_cancelDownload;
        private UpdateInfo m_updateInfo;

        protected override void CancelButton_Click(object sender, EventArgs e)
        {
            m_cancelDownload = true;
            base.CancelButton_Click(sender, e);
        }

        public VersionCheckForm(bool newVersionExists, UpdateInfo updateInfo):
            base()
        {
            InitializeComponent();

            if (updateInfo == null)
            {
                Logger.Log("updateInfo was null");
                messageLabel.Text = Resources.Resources.CouldNotObtainUpdateInfo;
                messageLabel.Height *= 2;
                linkLabel1.Visible = false;
                updateButton.Visible = false;
                CancelButtonVisable = false;
                OkButtonVisable = true;

                return;
            }

            m_updateInfo = updateInfo;

            updateButton.Click += new EventHandler(updateButton_Click);

            autoCheckCheckBox.Checked = ApplicationSettings.Default.CheckForUpdatesOnStartup;
            if (newVersionExists == false)
            {
                messageLabel.Text = Resources.Resources.NoUpdtatesAvailable;
                linkLabel1.Visible = false;
                updateButton.Visible = false;
                CancelButtonVisable = false;
                OkButtonVisable = true;
            }
            else
            {
                messageLabel.Text = String.Format("{0} {1}", Resources.Resources.UpdateIsAvailable, updateInfo.NewVersion);
                linkLabel1.Visible = true;
                updateButton.Visible = true;
                CancelButtonVisable = true;
                OkButtonVisable = false;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(m_updateInfo.VesionDocumentationUrl);
        }

        protected override void OnClosed(EventArgs e)
        {
            ApplicationSettings.Default.CheckForUpdatesOnStartup = autoCheckCheckBox.Checked;
            ApplicationSettings.Default.Save();
            base.OnClosed(e);
        }

        void updateButton_Click(object sender, EventArgs e)
        {
            updateButton.Enabled = false;
            autoCheckCheckBox.Visible = false;
            colorProgressBar1.Visible = true;
            colorProgressBar1.Value = 0;

            string downloadedUpgraderPath = Path.Combine(Path.GetTempPath(), ApplicationFolders.ApplicationUpgradeInstallerName);

            try
            {
                WebUtilities.DownloadFile(m_updateInfo.DownloadUrl, downloadedUpgraderPath, new ProgressEventDelegate(ProgressEventDelegate));
            }
            catch (Exception ex)
            {
                ApplicationAlert.Show(Resources.Resources.UpgradeDownloadFailed);
                Logger.Log(ex);
            }

            if (m_cancelDownload == true)
            {
                return;
            }

            try
            {
                string upgraderPath = Path.Combine(Application.StartupPath, ApplicationFolders.UpgraderMonitorFileName);
                string newUpgraderPath = Path.Combine(Path.GetTempPath(), ApplicationFolders.UpgraderRuningMonitorFileName);

                File.Copy(upgraderPath, newUpgraderPath, true);

                Process proc = Process.GetCurrentProcess();
                IntPtr handle = proc.Handle;
                if (!Win32Interop.SetHandleInformation(handle, 1, 1))
                {
                    Logger.Log("Upgrade faild...");
                    return;
                }
                
                string processId = handle.ToInt64().ToString(CultureInfo.InstalledUICulture);

                string arguments = string.Format("{0},\"{1}\",\"{2}\"",
                                                   processId,
                                                   Application.ExecutablePath,
                                                   downloadedUpgraderPath);

                ProcessStartInfo startInfo = new ProcessStartInfo(newUpgraderPath, arguments);
                startInfo.UseShellExecute = false;
                startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                startInfo.CreateNoWindow = true;
                Process.Start(startInfo).Dispose();

                Application.Exit();
            }
            catch (Exception ex)
            {
                File.Delete(downloadedUpgraderPath);
                Logger.Log(ex);
            }
        }

        private bool ProgressEventDelegate(int maximum, int value)
        {
            colorProgressBar1.Maximum = maximum;
            colorProgressBar1.Value = value;

            Application.DoEvents();
            return m_cancelDownload;
        }
    }
}